<template>
  <div class="add-dish">
    <header class="add-header">
      <el-page-header
        :content="id ? '编辑菜品' : '添加菜品'"
        @back="$router.back()"
      />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="form">
          <el-form
            ref="dishForm"
            label-width="120px"
            :model="dishForm"
            :rules="dishRules"
          >
            <!-- 菜品名称 -->
            <el-form-item label="菜品名称：" prop="name">
              <el-input
                v-model="dishForm.name"
                placeholder="请填写菜品名称"
                style="width: 300px"
              />
            </el-form-item>

            <!-- 菜品分类 -->
            <el-form-item label="菜品分类" prop="categoryId">
              <el-select v-model="dishForm.categoryId" style="width: 300px">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>

            <!-- 菜品价格（单位：分） -->
            <el-form-item label="菜品价格：" prop="price">
              <el-input
                v-model="dishForm.price"
                style="width: 300px"
                placeholder="请设置菜品价格"
              />
            </el-form-item>

            <!-- 口味做法配置 -->
            <!--思路？？？ -->
            <el-form-item label="口味做法配置：">
              <!-- 初始仅显示按钮，点击后显示完整配置区域 -->
              <div v-if="!showFlavorConfig" class="initial-btn">
                <el-button
                  type="primary"
                  style="background-color: #faad14; border-color: #faad14"
                  @click="showFlavorConfig = true"
                >
                  + 添加口味
                </el-button>
              </div>

              <!-- 点击后显示的配置区域 -->
              <div v-else class="flavor-container">
                <div class="flavor-header">
                  口味名（3个字内） 口味标签（输入标签回车添加）
                </div>
                <!-- 用flex容器包裹下拉、标签、输入框 -->
                <div class="flavor-row">
                  <el-select
                    v-model="dishForm.flavors[0].name"
                    placeholder="请输入口味"
                    class="flavor-select"
                  />
                  <el-input
                    placeholder="输入后回车添加"
                    class="tag-input"
                    style="width: auto; min-width: 100px"
                    @keyup.enter.native="addCustomTag"
                  >
                    />
                  </el-input>
                  <!-- 修改标签容器和输入框的样式 -->

                  <el-button
                    type="text"
                    style="color: #f56c6c"
                    @click="showFlavorConfig = false"
                  >
                    删除
                  </el-button>
                </div>
                <el-button
                  type="primary"
                  style="
                    background-color: #faad14;
                    border-color: #faad14;
                    margin-top: 10px;
                  "
                >
                  添加口味
                </el-button>
              </div>
            </el-form-item>
            <!-- 菜品图片 -->
            <!--:limit="1" 限制只能上传1张 -->
            <el-form-item label="菜品图片：" prop="image">
              <el-upload
                ref="upload"
                class="upload-demo"
                action="#"
                :limit="1"
                list-type="picture-card"
                :http-request="httpRequest"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>

            <!-- 菜品描述 -->
            <el-form-item label="菜品描述：">
              <el-input
                v-model="dishForm.description"
                type="textarea"
                placeholder="菜品描述，最长200字"
                style="width: 600px; height: 100px"
              />
            </el-form-item>
          </el-form>
        </div>
        <footer class="add-footer">
          <div class="btn-container">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" @click="saveForm">保存</el-button>
            <el-button
              type="primary"
              style="background-color: #000; border-color: #000"
              @click="saveAndContinue"
              >保存并继续添加菜品</el-button
            >
          </div>
        </footer>
      </div>
    </main>
  </div>
</template>

<script>
import {
  addDishAPI, // 新增菜品接口（需自行定义）
  editDishAPI, // 编辑菜品接口（需自行定义）
  getCategoryListAPI,
  getDishDetailAPI,
  uploadAPI
} from '@/api/dish'
import Pagination from '@/components/Pagination'
export default {
  components: { Pagination },
  data() {
    return {
      categoryList: [],
      dishForm: {
        status: 1,
        categoryId: '',
        code: '',
        name: '', // 菜品名称
        price: '', // 价格（单位：分）
        flavors: [
          {
            name: '辣度',
            showOption: false,
            value: '["不辣","微辣","中辣","重辣"]'
          }
        ], // 口味列表（对象数组：[{name: '辣度', value: '中辣'}, ...]）
        image: '', // 图片路径
        description: '' // 菜品描述
      },
      dishRules: {
        name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
        categoryId: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        price: [{ required: true, message: '请输入菜品价格', trigger: 'blur' }],
        image: [
          { required: true, message: '请上传菜品图片', trigger: 'change' }
        ]
      },
      showFlavorConfig: false, // 控制配置区域是否显示
      editRequestData: {} // 编辑时的原始数据
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  async created() {
    const res = await getCategoryListAPI()
    this.categoryList = res.data

    if (this.id) {
      this.getDishDetail()
    }
  },
  methods: {
    // 回显菜品详情
    async getDishDetail () {
      const res = await getDishDetailAPI(this.id)

      this.dishForm = res.data
      // this.dishForm.image = res.data.image

      // 图片路径？？
      const baseImageUrl = 'http://localhost:9528/dev-api/common/upload'
      const fullImageUrl = baseImageUrl + res.data.image
      this.dishForm.image = fullImageUrl
      // 2. 构造el-upload的文件列表，实现图片回显
      if (fullImageUrl) {
        const fileObj = {
          name: 'dish-image',
          url: fullImageUrl,
          uid: Date.now(),
          status: 'success'
        }
        this.$refs.upload.fileList = [fileObj]
      }
    },
    // 图片上传成功
    async httpRequest ({ file }) {
      const formData = new FormData()
      formData.append('file', file)
      // console.log(formData)
      const res = await uploadAPI(formData)
      this.dishForm.image = res.data
    },
    // 重置表单
    resetForm () {
      this.$refs.dishForm.resetFields()
      // this.flavors = []
      this.$router.back()
    },
    // 保存表单
    saveForm () {
      this.$refs.dishForm.validate(async valid => {
        if (!valid) return
        // 合并口味到表单
        // this.dishForm.flavors = this.flavors
        if (this.id) {
          await editDishAPI(this.dishForm)
          this.$message.success('编辑成功')
        } else {
          // 新增场景
          await addDishAPI(this.dishForm)
          this.$message.success('添加成功')
        }
        this.$router.back()
      })
    },
    // 保存并继续添加
    saveAndContinue () {
      this.$refs.dishForm.validate(async valid => {
        if (!valid) return
        // this.dishForm.flavors = this.flavors
        await addDishAPI(this.dishForm)
        this.$message.success('添加成功')
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles() // 清空上传组件内部的文件列表
        }
        this.dishForm.image = ''
        this.$refs.dishForm.resetFields()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.add-dish {
  background-color: #f4f6f8;
  // 去掉固定高度，改用最小高度，允许内容撑开并滚动
  min-height: 100vh;
  overflow-y: auto; // 内容溢出时显示滚动条
  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }
}

.add-main {
  background: #f4f6f8;
  padding: 20px 40px;

  .form-container {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    // 确保容器能完整包裹内容（包括底部按钮）
    overflow: hidden;

    .form {
      // 适当减小表单内边距，避免内容过高
      padding: 20px 40px;

      .el-form {
        .el-form-item {
          margin-bottom: 20px; // 减小表单项间距
        }
      }
    }

    .add-footer {
      padding: 16px 50px; // 减小底部按钮区域内边距
      text-align: center;
      border-top: 1px solid #eee;
      // 确保按钮区域在容器底部，不被遮挡
      position: relative;
      z-index: 10;
    }
  }
}

// 初始按钮样式
.initial-btn {
  .el-button {
    padding: 6px 15px;
    font-size: 12px;
  }
}

// 配置区域整体样式
.flavor-container {
  background-color: #f9f9f9;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 15px;
  width: 800px;

  .flavor-header {
    font-size: 14px;
    color: #606266;
    margin-bottom: 12px;
  }

  .tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
}
// 让两个输入框在一行显示的flex布局
.flavor-row {
  display: flex;
  gap: 10px; // 两个输入框之间的间距
  margin-bottom: 10px;
}

.flavor-select {
  width: 200px; // 口味下拉框宽度
}

.tag-input {
  flex: 1; // 标签输入框占剩余宽度
}
// 自定义标签样式
.custom-tag {
  background-color: #fff0f0;
  border-color: #ffccc7;
  color: #e53e3e;
  height: 28px;
  line-height: 28px;
  padding: 0 10px;
  font-size: 12px;

  ::v-deep .el-tag__close {
    color: #e53e3e;
    margin-left: 5px;
  }
}
// 调整标签容器的对齐方式
.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center; // 新增：标签与输入框垂直居中
  flex: 1; // 新增：占满剩余宽度，避免被挤压
}

// 调整输入框样式
.tag-input {
  // 移除flex: 1，改用min-width确保自适应
  min-width: 100px;
  width: auto;
}
// 上传样式
.el-upload--picture-card {
  width: 300px;
  height: 200px;
  border: 1px dashed #dcdcdc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
}

.el-upload--picture-card .el-upload__text {
  margin-top: 0;
  color: #333;
  font-size: 16px;
}
</style>
